const urljoin = require('url-join')

const request = (url, method, data) => {
    return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('api_token');

        uni.request({
            url: urljoin(getApp().globalData.apiBase, url),
            method: method,
            data: data,
            header: {
                'content-type': 'application/json',
                'X-Auth-Token': token
            },
            success: res => {
                console.log('Promise Raw Data:', method, url, res)

                if (!res.data.code && res.statusCode == 200) {
                  resolve(res.data.data);
                } else {
                  if (token) {
                    uni.showModal({
                       title: `出错了 (${res.data.message})`,
                    })
                  }
                  reject(res.data.message);
                }
              },
              error: err => {
                reject('Network error');
              }
        })
    })
}

export default {
    get: (url, data) => request(url, 'GET', data),
    put: (url, data) => request(url, 'PUT', data),
    post: (url, data) => request(url, 'POST', data),
    delete: (url, data) => request(url, 'DELETE', data),
}